package com.sdgakj.web.h5;

import com.sdgakj.entity.Family;
import com.sdgakj.entity.FamilyPerson;
import com.sdgakj.entity.Person;
import com.sdgakj.entity.User;
import com.sdgakj.service.family.FamilyService;
import com.sdgakj.service.person.PersonService;
import com.sdgakj.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.springframework.data.jpa.domain.AbstractPersistable_.id;

/**
 * Created by win10 on 2017/5/30.
 */
@Controller
@RequestMapping(value = "/h5/person")
public class H5PersonController {

    @Autowired
    private PersonService personService;
    @Autowired
    private UserService userService;
    @Autowired
    private FamilyService familyService;
    /**
     *添加亲人
     * */
    @RequestMapping(value="/addfamily",method = RequestMethod.POST)
    public void addFamily(Long userId,String liclick,String lastname,String fristname,
                          String gender,Integer alive,String borntime,@RequestParam(value = "tel",defaultValue = "0") String tel,
                          String wechat,Long shidai){
        System.out.println("添加亲属的id: "+userId);
/*        System.out.println("添加亲属的id: "+userId);
        System.out.println("下列是添加亲人的属性");
        System.out.println(liclick);
        System.out.println(lastname);
        System.out.println(fristname);
        System.out.println(gender);
        System.out.println(alive);
        System.out.println(borntime);
        System.out.println(tel);
        System.out.println(wechat);*/
  /*      Integer alive,String lastname,String fristname,
                          String gender,String bornTime,String tel,
                          String wechat*/
        /*
            liclick
         * 1 父母 2丈夫妻子 3 兄弟姐妹 4 儿子女儿
         * 首先查询增加亲属的id这个亲人 直接添加 完了在根据添加的类型 若是父母则修改 f 或者 m 的id
         *
         * */
        /*JSONObject jsonObject=new JSONObject();*/
        //首先根据手机号判断该亲属是否在本平台已经注册
        User user=null;
        Person person=null;
        if(tel!=null) {
            user= userService.getUserByMobile(tel);
        }
        if(user!=null){
            //如果用户不为空，说明该亲属已经注册了，找到他的person信息，修改其属性
            person=personService.getPersonByUserId(user.getId());
            if(person!=null) {
                addFamily(liclick, userId, person.getId());
            }
        }else {
            person =new Person();
            Long fmuv=0L;
            try {
                if(gender.equals("男")){
                    gender="M";
                }else {
                    gender="F";
                }
               // System.out.println("性别："+gender);
                person.setMobile(tel);
                person.setS(gender);
                person.setAlive(alive);
                person.setName(fristname);
                person.setFamilyName(lastname);
                person.setCreatetime(new Date());
                person.setUpdatetime(new Date());
                //父母配偶默认设置为0
                person.setM(fmuv);
                person.setF(fmuv);
                person.setUx(fmuv);
                person.setVir(fmuv);
                Family family=new Family();
                family.setId(0L);
                //添加亲属，返回亲属id,查找到用户信息,判断亲属的类型和性别来修改用户的性对应的字段
                Long familyId=personService.savePerson(person);//亲人
                //需要做person和user表的绑定
               /*  Person newUser=personService.getPersonById(familyId);
                User user=new User();
                user.setPerson(newUser);
                user.setName(newUser.getName());
                user.setRegisterDate(new Date());
                user.setDeltag("1");//先表示删除
                user.setPassword("123456");
                user.setPlainPassword("123456");
                long id=userService.saveUser(user);
                user=userService.getUserById(id);
                System.out.println("user:"+user);
                newUser.setUser(user);
                personService.updatePersonById(newUser);//修改亲属关联的userid*/
                person=personService.getPersonById(familyId);
                //修改person信息
                addFamily(liclick,userId,familyId);
                Person uperson=personService.getPersonByUserId(userId);
                if(uperson!=null) {
                    //在familyPerson 表中插入一条记录。
                    List<FamilyPerson> list = familyService.getFamilysByPersonId(uperson.getId());
                    if (list != null) {
                        for (FamilyPerson f : list) {
                            FamilyPerson fp = new FamilyPerson();
                            fp.setCreatetime(new Timestamp(new Date().getTime()));
                            fp.setUpdatetime(new Timestamp(new Date().getTime()));
                            fp.setFfName(f.getFfName());
                            fp.setFfId(f.getFfId());
                            fp.setFpId(person.getId());
                            fp.setGeneration(shidai);
                            fp.setState(1L);
                            familyService.saveFamilyPerson(fp);
                        }
                    }

                }
            }catch (Exception e){
               e.printStackTrace();
            }
        }
    }

    private void addFamily(String cases,Long userId,Long familyId){
        Person p=personService.getPersonByUserId(userId);//用户
        //在FamilyPerson表插入一条记录，通过用户id和家族id查询是否存在
        Person p1=personService.getPersonById(familyId);
        if(cases.equals("1")){
            //父母 如果是男 则修改用户的fater id 女则相反
            if(p1.getS().equals("M")){
                p.setF(p1.getId());
                if(p.getM()!=0){
                    //有母亲 改父亲妻子的id
                    p1.setUx(p.getM());
                }
            }else {
                p.setM(p1.getId());
                if(p.getF()!=0){
                    //有父亲 给母亲添加丈夫的id
                    p1.setVir(p.getF());
                }
            }
            personService.updatePersonById(p);
            personService.updatePersonById(p1);
        }else if(cases.equals("2")){
            //丈夫、妻子 如果是男则添加丈夫id 女则反之
            //添加妻子or丈夫通过性别 分别查找到 m or f 字段值是添加亲属的id集合
            if(p.getS().equals("M")){
                //孩子集合
                List<Person> list=personService.getPersonByFatherId(p.getId());
                if(list!=null){
                    for(Person li:list){
                        li.setM(familyId);
                        personService.updatePersonById(li);
                    }
                }
                p.setUx(familyId);//妻子
                p1.setVir(p.getId());//丈夫
            }else{
                List<Person> list=personService.getPersonByMatherId(p.getId());
                if(list !=null){
                    for(Person li:list){
                        li.setF(familyId);
                        personService.updatePersonById(li);
                    }
                }
                p.setVir(familyId);
                p1.setUx(p.getId());
            }
            personService.updatePersonById(p);
            personService.updatePersonById(p1);
        }else if(cases.equals("3")){
            //兄弟姐妹 找到自己父母的id 传给亲属
            p1.setF(p.getF());
            p1.setM(p.getM());
            personService.updatePersonById(p1);
        }else if(cases.equals("4")){
            //孩子 如果用户是男
            if(p!=null)
                if(p.getS().equals("M")){
                    p1.setF(p.getId());
                    if(p.getUx()!=null){
                        p1.setM(p.getUx());
                    }
                }else {
                    if(p.getVir()!=null) {
                        p1.setF(p.getVir());
                    }
                    p1.setM(p.getId());
                }
            }
            personService.savePerson(p1);
        }


    @RequestMapping(value = "newperson")
    public String newPerson(Long id, Model model){
        model.addAttribute("key",id);
        return "h5/family/editor";
    }
    /**
     * @param  userId  用户id
     * @param  pic    图片地址
     * @param  name  姓名
     * @param  s     性别
     * @param  mobile  手机
     * @param  bornTime  生日
     * @param  bornAddress  住址
     * */
    @RequestMapping(value = "updatePerson",method = RequestMethod.POST)
    public void updatePerson(Long userId, String pic, String name, String s,
                               String mobile, String bornTime, String bornAddress,
                               @RequestParam(value = "zuji",required = false) String zuji) throws ParseException {
        Person person=personService.getPersonByUserId(userId);
        if(person!=null){
            person.setAvatar(pic);
           /* User user=userService.getUserById(userId);
            if(user!=null){
                user.setName(name);
            }*/
            /*else{
                user=new User();
                user.setName(name);
                user.setPassword("123456");
                user.setPlainPassword("123456");
                user.setPerson(person);
                user.setSex(s);
                user.setType("1");//普通用户
            }*/
            /*person.setUser(user);*/
            person.setName(name);
            if(s.equals("男")){
                s="M";
            }else {
                s="F";
            }
            person.setS(s);
            person.setMobile(mobile);
         //   SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           // Date date= (Date) sdf.parse(bornTime);
            person.setBornTime(bornTime);
            person.setBornAddress(bornAddress);
            person.setAncestralHome(zuji);
            personService.updatePersonById(person);
        }
      //  return "h5/user/myself";

    }


    @RequestMapping("/treeaddfamily")
    public void treeAddFamily(@RequestParam(value = "personId",required = true) Long personId,
                              @RequestParam(value = "familyId",required = true) Long familyId,
                              @RequestParam(value = "relation",required = true)int relation,Model model){
        Person person=personService.getPersonById(personId);
        Person family=personService.getPersonById(familyId);
        if(person!=null && family!=null){
            //表示两个人存在
            if(relation==1){
                //表示父
                person.setF(family.getId());
                personService.updatePersonById(person);
            }
            if(relation==2){
                //母亲
                person.setM(family.getId());
                personService.updatePersonById(person);
            }
            if(relation==3){
                //丈夫添加妻子
                person.setUx(family.getId());
                family.setVir(person.getId());
                personService.updatePersonById(person);
                personService.updatePersonById(family);
            }
            if(relation==4){
                //妻子添加丈夫
                person.setVir(family.getId());
                family.setUx(person.getId());
                personService.updatePersonById(person);
                personService.updatePersonById(family);

            }
    /*        if(relation==5){
                //兄弟 第一行确定父母都存在 第二行判断 父亲存在或者母亲存在
                if((person.getF()!=null && person.getM()!=null && person.getF()!=0 && person.getM()!=0) ||
                        ((person.getF()!=null && person.getF()!=0) || (person.getM()!=null && person.getM()!=0))
                        ){
                    family.setF(person.getF());
                    family.setM(person.getM());
                    personService.updatePersonById(family);
                }
            }*/
            if(relation==5){
                //孩子
                if(person.getS().equals("M")){
                    family.setF(person.getId());
                    family.setM(person.getUx());
                }else {
                    family.setM(person.getId());
                    family.setF(person.getVir());
                }
                personService.updatePersonById(family);
            }
        }

    }
    //管理员通过家族人员指定关系
    @RequestMapping(value = "/addfamilybyadmin",method = RequestMethod.GET)
    public String addFamilyByAdmin(@RequestParam(value = "familyId",required = false) Long familyId,
                                   @RequestParam(value = "relactionId",required = true) Long relactionId,
                                   @RequestParam(value = "personId",required = true)Long personId,Model model){
        //通过家族id和personid查询到家族成员！
        List<FamilyPerson> familyPersons=familyService.getPersonByFfIdAndState(familyId);
        List<Person> list=new ArrayList<>();//家族人没有在家族树的集合
        //根据选择添加的亲属类型来判断显示什么人
        //@relactionId 1：父亲，2：母亲，3：妻子，4：丈夫，5：孩子
        if(relactionId==1){
            for(FamilyPerson f:familyPersons){
                Person person=personService.getPersonById(f.getFpId());
                if(person.getS().equals("M") && person.getId()!=personId ){
                    list.add(person);
                }
            }
        }
        if(relactionId==2){
            for(FamilyPerson f:familyPersons){
                Person person=personService.getPersonById(f.getFpId());
                if(person.getS().equals("F") && person.getId()!=personId ){
                    list.add(person);
                }
            }
        }
        if(relactionId==3){
            for(FamilyPerson f:familyPersons){
                Person person=personService.getPersonById(f.getFpId());
                if(person.getS().equals("F") && (person.getVir()==0 || person.getVir()==null) && person.getId()!=personId ){
                    list.add(person);
                }
            }
        }
        if(relactionId==4){
            for(FamilyPerson f:familyPersons){
                Person person=personService.getPersonById(f.getFpId());
                if(person.getS().equals("M") && (person.getUx()==0 || person.getUx()==null) ){
                    list.add(person);
                }
            }
        }
        if(relactionId==5){
            for(FamilyPerson f:familyPersons){
                Person person=personService.getPersonById(f.getFpId());
                if(person.getId()!=personId) {
                    list.add(person);
                }
            }
        }

        model.addAttribute("list",list);
        model.addAttribute("familyId",familyId);//家族id
        model.addAttribute("relactionId",relactionId);//关系
        model.addAttribute("personId",personId);//管理员指定的用户
        return "h5/user/member_edit";
    }

}
